package boardgamer.yavalath.common;

import boardgamer.common.GameLog;
import boardgamer.common.GameUpdate;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;

import java.io.Serializable;

import static boardgamer.yavalath.common.YavalathGameStateChange.Event.START_GAME;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class YavalathReplay implements Serializable {

  private static final long serialVersionUID = -7309287427844621316L;

  private final ImmutableList<GameUpdate<YavalathGameState, YavalathGameStateChange>> changes;
  
  public YavalathReplay(GameLog<YavalathGameState, YavalathGameStateChange> gameLog) {
    ImmutableList<GameUpdate<YavalathGameState, YavalathGameStateChange>> allUpdates
        = gameLog.getUpdates(0);

    // Find the last index before "start game"
    Integer lastIndex = null;
    for (int i = 0; i < allUpdates.size(); i++) {
      YavalathGameStateChange stateChange = allUpdates.get(i).getStateChange();
      if (stateChange != null && stateChange.getEvent() == START_GAME) {
        lastIndex = i;
        break;
      }
    }
    checkNotNull(lastIndex, "Cannot find START_GAME event");
    
    this.changes = allUpdates.subList(lastIndex, allUpdates.size());
  }

  @VisibleForTesting ImmutableList<GameUpdate<YavalathGameState, YavalathGameStateChange>>
      getAllChanges() {
    return ImmutableList.copyOf(changes);
  }
  
  public int getChangeCount() {
    return changes.size();
  }
  
  public GameUpdate<YavalathGameState, YavalathGameStateChange> getChange(int index) {
    return changes.get(index);
  }

  public YavalathGameState getInitialGameState() {
    return changes.get(0).getEndState();
  }
}
